#include "widget.h"
#include<QFont>
#include<QGridLayout>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    display=new QLineEdit("0");//初始为0

    display->setReadOnly(true);
    display->setAlignment(Qt::AlignRight);//右对齐
    display->setMaxLength(15);//限制计算长度

    QFont font=display->font();
    font.setPointSize(font.pointSize()+8);
    display->setFont(font);//调整字体大小，不然太小了

    for(int i=0;i<10;++i)
    {
        digitButtons[i]=createButton(QString::number(i),SLOT(digitClicked()));//传递数字字符串
    }

    Button* pointBtn=createButton(".",SLOT(pointClicked()));//小数点
    Button* backspaceBtn=createButton("BackSpace",SLOT(backSpaceClicked()));//退格
    Button* clearBtn=createButton("clear",SLOT(clear()));//清除一位
    Button* clearAllBtn=createButton("clear all",SLOT(clearAll()));//清空所有
    //四则运算
    Button* divBtn=createButton("\303\267",SLOT(muliplicativeOperatorClicked()));//除法，用编码找除号÷
    Button* timesBtn=createButton("\303\227",SLOT(muliplicativeOperatorClicked()));//乘法，用编码找乘号×

    Button* minusBtn=createButton("-",SLOT(additiveOperatorClicked()));//减法
    Button* plusBtn=createButton("+",SLOT(additiveOperatorClicked()));//加法

    //特殊运算
    Button* sqrtBtn=createButton("Sqrt",SLOT(unaryOperatorClicked()));//开平方，直接用Sprt表示
    Button* powerBtn=createButton("x\302\262",SLOT(unaryOperatorClicked()));//平方，用编码找平方²
    Button* reciprocalBtn=createButton("1/x",SLOT(unaryOperatorClicked()));//取倒数，可以和取平方用一个常函数
    Button* equalBtn=createButton("=",SLOT(equalClicked()));//等于号，算结果

    Button* changeBtn=createButton("\302\261",SLOT(changeClicked()));//改变正负号

    //对按钮进行布局，网格布局
    auto mainLayout=new QGridLayout(this);

    mainLayout->addWidget(display,0,0,1,7);
    //三个基础按钮
    mainLayout->addWidget(backspaceBtn,1,0,1,2);
    mainLayout->addWidget(clearBtn,1,2,1,2);
    mainLayout->addWidget(clearAllBtn,1,4,1,3);

    mainLayout->addItem(new QSpacerItem(20,40,QSizePolicy::Expanding),2,0);


    //其他按钮进行摆放和布局
    for(int i=1;i<10;++i)
    {
        int row=((9-i)/3)+2;
        int col=((i-1)%3)+1;
        mainLayout->addWidget(digitButtons[i],row,col);
    }

    mainLayout->addWidget(digitButtons[0],5,1);
    mainLayout->addWidget(pointBtn,5,2);
    mainLayout->addWidget(changeBtn,5,3);

    mainLayout->addWidget(divBtn,2,4);
    mainLayout->addWidget(timesBtn,3,4);
    mainLayout->addWidget(minusBtn,4,4);
    mainLayout->addWidget(plusBtn,5,4);

    mainLayout->addWidget(sqrtBtn,2,5);
    mainLayout->addWidget(powerBtn,3,5);
    mainLayout->addWidget(reciprocalBtn,4,5);
    mainLayout->addWidget(equalBtn,5,5);
    //居中
    mainLayout->addItem(new QSpacerItem(20,40,QSizePolicy::Expanding),3,6);




void Widget::abortOperator()
{
    clearAll();
    display->setText("#####");
}

